//
//  StringHelper.swift
//  CommonTools
//
//  Created by xianquan on 2023/12/12.
//

import Foundation

public extension String {
    var upperFirstLetter:String{
        return String(prefix(1).capitalized +
                      dropFirst())
    }
    
    func width(for font: XWFontProvide) -> CGFloat {
        let nsStr = self as NSString
        return nsStr.width(for: font.font)
    }
    
    func height(for font: XWFontProvide, width: CGFloat) -> CGFloat {
        let nsStr = self as NSString
        return nsStr.height(for: font.font, width: width)
    }
    
    
    
}

public extension String {
    func ranges(of string: String) -> [Range<String.Index>] {
        var rangeArray = [Range<String.Index>]()
        var searchedRange: Range<String.Index>
        guard let sr = self.range(of: self) else {
            return rangeArray
        }
        searchedRange = sr
        
        var resultRange = self.range(of: string, range: searchedRange, locale: nil)
        while let range = resultRange {
            if string.isEmpty {
                break
            }
            rangeArray.append(range)
            searchedRange = Range(uncheckedBounds: (range.upperBound, searchedRange.upperBound))
            resultRange = self.range(of: string, range: searchedRange, locale: nil)
        }
        return rangeArray
    }
    
    func nsrange(fromRange range : Range<String.Index>) -> NSRange {
        return NSRange(range, in: self)
    }
    
    func nsranges(of string: String) -> [NSRange] {
        return ranges(of: string).map { (range) -> NSRange in
            self.nsrange(fromRange: range)
        }
    }
}

public extension String {
    /// 验证输入结果
    enum ValidateType: String {
        /// 判断6-16位字母，数字
        case userName = "^[a-zA-Z0-9]{6-16}+$"
        /// 中文，字母，数字
        case nickName = "^[\\u4E00-\\u9FA5A-Za-z0-9]+$"
        /// 判断手机号
        case phoneNum = "^1[3-9]\\d{9}$"
        /// 判断是否6-16位，包含数字和字母
        case password = "^(?=.*[0-9])(?=.*[a-zA-Z])[^\\p{Han}].{8,16}$"
        /// 判断是否4位验证码
        case authCode = "^[0-9]{6}+$"
        /// 判断是否标点符号
        case punctuation = "[\\p{P}]+"
        case emoji = "^[\\u4E00-\\u9FA5A-Za-z0-9\n@$&^ \\p{P}]+$"
    }
    func validate(_ type: ValidateType) -> Bool{
        
        let predicate = NSPredicate(format: "SELF MATCHES %@", type.rawValue)
        return predicate.evaluate(with: self)
    }
    
    
}

public extension String {
    /// 限定输入
    enum Pattern: String{
        case none = ""
        case num = "[^0-9]"
        case cn = "[^\\u4E00-\\u9FA5， ]"
        case en = "[^A-Za-z' ]"
        case enNum = "[^A-Za-z'0-9 ]"
        case enNumUnderline = "[^A-Za-z'0-9_ ]"
        case encn = "[^A-Za-z\\u4E00-\\u9FA5 ]"
        case email = "[^A-Za-z0-9@.]"
        case notCn = "[\\p{Han}]+$"
    }
    
    func regularReplace(_ type: Pattern, with: String, options: NSRegularExpression.Options = []) -> String{
        if let regex = try? NSRegularExpression(pattern: type.rawValue, options: options) {
            return regex.stringByReplacingMatches(in: self, options: [], range: NSRange(location: 0, length: count), withTemplate: with)
        }
        return ""
    }
}

public extension String{
    func toJsonDictionary() -> [String : Any]{
        toJsonContainer() as? [String : Any] ?? [:]
    }
    func toJsonArray() -> [Any] {
        toJsonContainer() as? [Any] ?? []
    }
    func toJsonContainer () -> Any? {
        if let data = self.data(using: .utf8) {
            do {
                let value = try JSONSerialization.jsonObject(with: data, options: [])
                return value
            } catch {
                XWLog(value: "发生错误：\(error)")
            }
        } else {
            XWLog(value: "无效的JSON字符串")
        }
        return nil
    }
}



public extension CustomStringConvertible {
    var descriptionByUnicode: String {
        if XWClassRoomManager.logType == .none {
            return ""
        }
        var str1 = description.replacingOccurrences(of: "\\u", with: "\\U")
        let temp = "xxxtempxxx"
        str1 = str1.replacingOccurrences(of: "\\\"", with: temp)
        str1 = str1.replacingOccurrences(of: "\"", with: "\\\"")
        str1 = str1.replacingOccurrences(of: temp, with: "\\\"")
        str1 = "\"".appending(str1).appending("\"")
        guard let data = str1.data(using: .utf8) else {return ""}
        var returnStr = ""
        do {
            returnStr = try PropertyListSerialization.propertyList(from: data, format: nil) as! String
        }
        catch {
            XWLog(value: "转换unicode失败：\(error)")
        }
        return returnStr
    }
}

public extension String {
    func extractImageSrc() -> String? {
        // 正则表达式用于匹配<img>标签中的src属性
        let regex = try! NSRegularExpression(pattern: "<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>", options: .caseInsensitive)
        let results = regex.matches(in: self, options: [], range: NSRange(location: 0, length: utf16.count))
        
        // 获取第一个匹配的结果
        if let result = results.first {
            // 提取src属性中的URL
            let urlRange = result.range(at: 1)
            let startIndex = index(startIndex, offsetBy: urlRange.location)
            let endIndex = index(startIndex, offsetBy: urlRange.length)
            return String(self[startIndex..<endIndex])
        }
        return nil
    }
    
    
    var containsHTMLTags: Bool {
        let htmlTagPattern = "<[^>]+>"
        let htmlTagRegex = try! NSRegularExpression(pattern: htmlTagPattern)
        let range = NSRange(location: 0, length: utf16.count)
        let matches = htmlTagRegex.matches(in: self, options: [], range: range)
        return matches.count > 0
    }
    
    var hasPunctuationSuffix: Bool {
        let punctuationCharacters = CharacterSet.punctuationCharacters
        if let scalar = last?.unicodeScalars.first {
            return punctuationCharacters.contains(scalar)
        }
        return false
    }
    
    func removeNumericPrefix() -> String {
        let pattern = "^\\d+"
        let regex = try! NSRegularExpression(pattern: pattern)
        let range = NSRange(location: 0, length: utf16.count)
        let result = regex.stringByReplacingMatches(in: self, range: range, withTemplate: "")
        return result
    }
    
    func containsChinese() -> Bool {
        
        for (_, value) in self.enumerated() {

            if ("\u{4E00}" <= value  && value <= "\u{9FA5}") {
                return true
            }
        }
        
        return false
    }

    func extractChineseCharacters() -> [String] {
        do {
            let regex = try NSRegularExpression(pattern: "[\\u4e00-\\u9fff]+", options: .caseInsensitive)
            let nsString = self as NSString
            let matches = regex.matches(in: self, options: [], range: NSRange(location: 0, length: nsString.length))
            return matches.map { nsString.substring(with: $0.range)}
        } catch {
            print("Invalid regex: \(error.localizedDescription)")
            return []
        }
    }
}

public extension String {
    func maskPhoneNumber() -> String {
        let phoneNumber = self
        let phoneLength = phoneNumber.count
        if phoneLength == 11 {
            let startIndex = phoneNumber.startIndex
            let endIndex = phoneNumber.index(phoneNumber.startIndex, offsetBy: 3)
            let endIndex2 = phoneNumber.index(phoneNumber.endIndex, offsetBy: -4)
            
            let startString = phoneNumber[startIndex..<endIndex]
            let endString = phoneNumber[endIndex2..<phoneNumber.endIndex]
            
            return String(startString) + "****" + String(endString)
        }
        return phoneNumber
    }
}
